<template>
	<view class="setting-box">
		<view>
			<image src="/static/images/left.png" class="left-icon" @click="backToLast"></image>
		</view>
		<!-- 信息展示 -->
		<view class="top-box">
			<view class="avatar-box">
				<u-avatar :src="userShortInfo.avatarUrl" size="200rpx" alt="avatar"></u-avatar>
				<!-- <image :src="userShortInfo.avatarUrl" class="avatar-style" alt="avatar"></image> -->
			</view>
			<view class="info-box">
				<view class="name-style">{{ userShortInfo.user_name }}</view>
				<view class="name-style">{{ userShortInfo.dpl_id }}</view>
			</view>
		</view>
		<view style="background: linear-gradient(180deg, rgba(255, 255, 255, 0.6) 0%, rgba(255, 255, 255, 1) 100%);height: 100%;">
			<!-- 折叠面板 -->
			<view style="height:90%">
				<scroll-view scroll-y class="options-scroll">
					<up-collapse style="background-color: #fff;" accordion>
						<up-collapse-item :title="$t('accountSetting')" name="账号设置">
							<view class="collapse-item-row" @click="goSettingInfo">{{ $t('personalAccountInfo') }}
							</view>
							<view class="collapse-item-row-last" @click="goUpdatePassword()">{{ $t('changePassword') }}
							</view>
							<!-- <view class="collapse-item-row-last">{{$t('setting.list.item1-3')}}</view> -->
						</up-collapse-item>
						<up-collapse-item :title="$t('language')" name="语言">
							<view class="collapse-item-row" @click="switchLanguage('cn')">{{ $t('simplifiedChinese') }}
							</view>
							<view class="collapse-item-row-last" @click="switchLanguage('en')">{{ $t('english') }}
							</view>
						</up-collapse-item>
						<up-collapse-item :title="$t('suggestionFeedback')" name="意见反馈">
							<view class="collapse-item-row-last" @click="goFeedback">{{ $t('feedbackSquare') }}</view>
						</up-collapse-item>
						<up-collapse-item :title="$t('generalSettings')" name="通用设置">
							<view class="collapse-item-row-last" @click="goRightSetting()">{{ $t('privacyPermissions') }}
							</view>
							<!-- 通知管理 -->
							<!-- <view class="collapse-item-row" style="padding: 0.2rem;" @click="goMessageSetting()">
								{{ $t('messageSetting') }}
							</view> -->
							<!-- <view class="collapse-item-row-last" @click="clearCache">
								<view style="display: flex;justify-content: space-between;">
									<view>{{ $t('clearCache') }}</view>
									<view>{{ formattedCacheSize }}</view>
								</view>
							</view> -->
						</up-collapse-item>
						<up-collapse-item :title="$t('PoliciesAndAgreements')" name="政策与协议">
							<view class="collapse-item-row" @click="goHtml(0)">{{ $t('privacyPolicy') }}</view>
							<view class="collapse-item-row" style="padding: 0.2rem;" @click="goHtml(1)">
								{{ $t('userAgreement') }}
							</view>
							<view class="collapse-item-row" style="padding: 0.2rem;" @click="goHtml(2)">
								{{ $t('thirdPartySharing') }}
							</view>
							<view class="collapse-item-row-last" @click="goHtml(3)">{{ $t('personalInformation') }}
							</view>
						</up-collapse-item>
						<up-collapse-item :title="$t('about')" name="关于">
							<view class="collapse-item-row" @click="goHtml(6)">{{$t('aboutReport')}}</view>
							<view class="collapse-item-row" @click="goHtml(4)" style="padding: 0.2rem;">{{ $t('aboutDapiaoliang') }}</view>
							<view class="collapse-item-row" style="padding: 0.2rem;" @click="goHtml(5)">
								{{ $t('aboutApp') }}
							</view>
							<view class="collapse-item-row-last">{{ $t('currentVersion') }}</view>
						</up-collapse-item>
						<up-collapse-item :title="$t('logout')" name="退出登录">
							<view class="collapse-item-row-last" @click="isLogOut=true">{{ $t('logout') }}</view>
						</up-collapse-item>
					</up-collapse>
				</scroll-view>
			</view>

			<!-- 按钮 -->
			<!-- <view class="btn-box">
				<button class="btn-style" @click="logout">{{ $t('logout') }}</button>
			</view> -->

			<!-- 弹窗 -->
			<view class="popup-container1" v-if="isLogOut">
				<view class="popup-content1">
					<view style="text-align: center;">
						<image src="/static/images/logo.png" class="popup-image1"></image>
						<view class="tip-style1">{{$t('tipsLogout')}}</view>
						<view style="display: flex;">
							<button class="popup-button1" style="background-color: #9A9A9A;"
								@click="isLogOut=false">{{$t("cancel")}}</button>
							<button class="popup-button1" @click="logout">{{$t("confirm")}}</button>
						</view>
					</view>
				</view>
			</view>

			<!-- 清除缓存弹窗 -->
			<view v-if="isClear" class="popup-container">
				<view class="popup-content">
					<view style="text-align: center;">
						{{ $t('haveClearCache') }}
					</view>
				</view>
			</view>
		</view>
	</view>

</template>

<script setup lang="ts">
	import { computed, onMounted, ref } from 'vue'
	import { useCommonStore } from "@/stores/useCommonStore";
	import { onLoad, onShow } from "@dcloudio/uni-app";
	import { getFull } from "@/api/meApi/me.js"
	import { logoutAccount } from '@/api/setting/setting.js'
	import { useI18n } from 'vue-i18n'
	const { t } = useI18n()
	// import { getCacheSize, clearCache } from '@/utils/cacheUtils';
	// import DplCacheCleaner from '@/uni_modules/dpl-cache-cleaner/utssdk'
	// import type { CacheStats, ClearResult } from '@/uni_modules/dpl-cache-cleaner/utssdk'
	// 定义原生插件模块（仅在 App 环境下有效）
	let tClearCache = null;
	// let dplClearCache = null
	// 初始化原生插件（仅在 App 环境下执行）
	function initNativeModule() {
		console.log("1111111111", uni.getSystemInfoSync().platform)
		if (uni.getSystemInfoSync().platform === 'android') {
			try {
				tClearCache = uni.requireNativePlugin('TFKJ-ClearCache');
				// dplClearCache = uni.requireNativePlugin('dplClearCache');
				console.log('原生缓存插件初始化成功');
			} catch (error) {
				console.error('加载原生缓存插件失败:', error);
				uni.showToast({
					//  缓存功能不可用
					title: t('cacheUnavailable'),
					icon: 'none'
				});
			}
		} else {
			console.log('非app环境');
		}
	}
	onShow(() => {
		getUserData()
		// initNativeModule()
		// getCacheInfo()
	})
	interface ShortInfo {
		avatarUrl : string,
		dpl_id : string,
		user_name : string
	}
	const isClear = ref<Boolean>(false)
	const isLogOut = ref<Boolean>(false)
	const userShortInfo = ref<ShortInfo>({
		avatarUrl: '',
		dpl_id: '',
		user_name: ''
	})
	const cacheInfo = ref(null)
	const formattedCacheSize = ref('0.0 MB')
	// 获取缓存信息
	function getCacheInfo() {
		// 检查是否在 App 环境且插件已加载
		if (!isAppPlusEnv()) {
			showNonAppToast();
			return;
		}
		// dplClearCache.getTotalCacheSize(res => {
		// 	console.log('缓存大小', res.size);
		// 	formattedCacheSize.value = res.size
		// });
		tClearCache.TFKJ_GetTotalChacheSize(result => {
			console.log("缓存大小", result);
			formattedCacheSize.value = result.size
		});
	}
	function clearCache() {
		// 检查是否在 App 环境且插件已加载
		if (!isAppPlusEnv()) {
			showNonAppToast();
			return;
		}
		if (formattedCacheSize.value == "0.0 MB") {
			//提示"暂无可清理的缓存"
			uni.showToast({
				title:t('noCache'),
				icon:"none"
			})
		}
		else {
			uni.showLoading({
				// 清理中...
				title: t('cleaning')
			});
			try {
				console.log("缓存插件运行")
				tClearCache.TFKJ_ClearCacheData(result => {
					// dplClearCache.clearCache(res => {
					uni.hideLoading();
					// console.log('清理结果', res.success);
					console.log("清空缓存", result);
					isClear.value = true
					formattedCacheSize.value = "0.0 MB"
					// 记录开始时间
					const startTime = Date.now()
					let remainingTime = 1// 倒计时秒数
					// 创建定时器更新倒计时
					const timer = setInterval(() => {
						const elapsed = Math.floor((Date.now() - startTime) / 1000)
						remainingTime = 1 - elapsed

						if (remainingTime <= 0) {
							clearInterval(timer)
							isClear.value = false // 重置清除状态
						}
					}, 1000)
				});
			} catch (err) {
				console.log("缓存插件出错，2秒关闭加载动画")
				setTimeout(() => {
					uni.hideLoading();
					formattedCacheSize.value = "0.0 MB"
					isClear.value = true
					// 记录开始时间
					const startTime = Date.now()
					let remainingTime = 1// 倒计时秒数
					// 创建定时器更新倒计时
					const timer = setInterval(() => {
						const elapsed = Math.floor((Date.now() - startTime) / 1000)
						remainingTime = 1 - elapsed

						if (remainingTime <= 0) {
							clearInterval(timer)
							isClear.value = false // 重置清除状态
						}
					}, 1000)
				}, 2000) // 延迟 2秒关闭动画
			}
		}
	}
	// 检查是否为 App 环境且插件已加载
	function isAppPlusEnv() {
		return uni.getSystemInfoSync().platform === 'android' && tClearCache !== null;
	}
	// 显示非 App 环境提示
	function showNonAppToast() {
		uni.showToast({
			// 缓存功能仅在 App 中可用
			title: t('appClearCache'),
			icon: 'none'
		});
	}
	// 获取缓存信息
	// function getCacheInfo() {
	// DplCacheCleaner.getCacheInfo({
	// 	success: (stats) => {
	// 		formattedCacheSize.value = DplCacheCleaner.formatSize(stats.totalSize)
	// 		console.log('总缓存大小:', DplCacheCleaner.formatSize(stats.totalSize))
	// 		console.log('文件数量:', stats.totalCount)
	// 		cacheInfo.value = stats
	// 	},
	// 	fail: (error) => {
	// 		console.error('获取缓存信息失败:', error)
	// 	}
	// })
	// }
	// // 清理临时缓存
	// function clearTempCache() {
	// 	DplCacheCleaner.clearCache({
	// 		types: ['temp'],
	// 		success: (result) => {
	// 			console.log('清理成功:', result.message)
	// 			console.log('清理大小:', DplCacheCleaner.formatSize(result.clearedSize))
	// 		},
	// 		fail: (error) => {
	// 			console.error('清理失败:', error)
	// 		}
	// 	})
	// }

	// // 清理全部缓存
	// function clearAllCache() {
	// 	DplCacheCleaner.clearCache({
	// 		types: ['all'],
	// 		success: (result) => {
	// 			console.log('全部清理完成:', result.message)
	// 		}
	// 	})
	// }

	// // 同步获取缓存大小
	// function getTotalSize() {
	// 	const size = DplCacheCleaner.getTotalCacheSize(['image', 'temp'])
	// 	console.log('缓存大小:', DplCacheCleaner.formatSize(size))
	// }
	// // 清除缓存
	// function clearCache() {
	// 	// 清除缓存
	// 	// clearAllCache()
	// 	// uni.clearStorageSync(); 
	// 	console.log('缓存已清除');
	// 	// 清除成功
	// 	isClear.value = true
	// 	// 记录开始时间
	// 	const startTime = Date.now()
	// 	let remainingTime = 1// 倒计时秒数
	// 	// 创建定时器更新倒计时
	// 	const timer = setInterval(() => {
	// 		const elapsed = Math.floor((Date.now() - startTime) / 1000)
	// 		remainingTime = 1 - elapsed

	// 		if (remainingTime <= 0) {
	// 			clearInterval(timer)
	// 			isClear.value = false // 重置清除状态
	// 		}
	// 	}, 1000)
	// }

	function getUserData() {
		getFull().then(res => {
			console.log('获取用户信息 setting full', res);
			userShortInfo.value.avatarUrl = res.data.avatarUrl
			userShortInfo.value.dpl_id = res.data.dplID
			userShortInfo.value.user_name = res.data.username
		})
	}

	const backToLast = () => {
		uni.navigateBack()
	}
	function goSettingInfo() {
		uni.navigateTo({
			url: '/pages/setting/settingInfo'
		})
	}
	function goUpdatePassword() {
		uni.navigateTo({
			url: `/pages/setting/bindPhone` // 使用反引号
		})
	}
	function goFeedback() {
		uni.navigateTo({
			url: '/pages/setting/feedback'
		})
	}
	function goRightSetting() {
		uni.navigateTo({
			url: '/pages/setting/settingPrivacy'
		})
	}

	function goMessageSetting() {
		uni.navigateTo({
			url: '/pages/setting/messageNotification'
		})
	}

	function goHtml(i : number) {
		uni.navigateTo({
			url: `/pages/setting/html?index=${i}`
		})
	}

	const { locale } = useI18n()
	const commonStore = useCommonStore();
	const switchLanguage = (lang : string) => {
		if (lang === "cn") {
			locale.value = 'cn'
			commonStore.setLang("cn")
		} else if (lang === "en") {
			locale.value = 'en'
			commonStore.setLang("en")
		}
	}

	function logout() {
		logoutAccount().then((res) => {
			if (res && res.code == 200) {
				isLogOut.value = false
				uni.redirectTo({
					url: '/pages/login/login'
				})

				// 清除缓存
				uni.removeStorageSync('token')
				uni.setStorageSync('refreshToken', '')
				uni.setStorageSync('accessTokenExp', '')
				uni.setStorageSync('avatarUrl', '')
				uni.setStorageSync('username', '')
				uni.setStorageSync('userCode', '')
				uni.setStorageSync('dplID', '')
				uni.removeStorageSync('lang');
				uni.setStorageSync('userPhone', '')

				uni.showToast({
					// title: res.msg, 退出成功
					title: t('logoutSucess'),
					icon: 'none',
					duration: 1500
				})
			} else {
				uni.showToast({
					title: res.msg,
					icon: 'none',
					duration: 1500
				})
			}
		})
	}
</script>

<style lang="scss" scoped>
	.setting-box {
		width: 100%;
		height: 100%;
		/*微信小程序无法使用本地资源图片作为背景图 使用base64格式*/
		// background-image: url('');
		// background-size: cover;
		// background-repeat: no-repeat;
		box-sizing: border-box;
		padding: 2rem 0;
		/* #ifdef  MP-WEIXIN*/
		padding-top: 3.5rem;
		/* #endif*/
	}

	.left-icon {
		width: 1.5rem;
		height: 1.5rem;
		margin: 0rem 0 0 0.5rem;
		/* #ifdef  MP-WEIXIN*/
		margin: 0rem 0 0 0.5rem;
		/* #endif*/
	}

	.top-box {
		// width: 24.56rem;
		height: 9.5rem;
		background: linear-gradient(180deg, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 1) 100%);
		display: flex;
		position: relative;
	}

	.avatar-box {
		margin-left: 1.13rem;
	}

	.avatar-style {
		width: 6.25rem;
		height: 6.25rem;
		border-radius: 50%;
	}

	.info-box {
		width: 100%;
		margin: 1.2rem 0 0 1rem;
		color: rgba(16, 16, 16, 0.8);
		font-size: 0.88rem;
		font-weight: 600;
		text-align: left;
	}

	.name-style {
		height: 1.88rem;
		line-height: 1.88rem;
		margin-bottom: 0.5rem;
		width: 85%;
		overflow: hidden;
		text-overflow: ellipsis;
		/* display: -webkit-box;
		-webkit-line-clamp: 1;
		-webkit-box-orient: vertical; */
		white-space: nowrap; /* 简化为单行截断 */
	}

	.icon-style {
		width: 1.5rem;
		height: 1.5rem;
	}

	.qrcode-box {
		position: absolute;
		top: 1rem;
		right: 0.81rem;
	}

	.edit-box {
		position: absolute;
		bottom: 0.95rem;
		right: 0.81rem;
	}

	.options-scroll {
		height: 80%;
	}

	.collapse-item-row {
		padding: 0 0.2rem;
		width: 100%;
		height: 2.5rem;
		line-height: 2.5rem;
		border-bottom: 1px solid #eee;
	}

	.collapse-item-row-last {
		padding: 0 0.2rem;
		width: 100%;
		height: 2.5rem;
		line-height: 3rem;
	}

	.btn-box {
		display: flex;
		position: absolute;
		bottom: 1rem;
		left: 1%;
		right: 1%;
	}

	.btn-style {
		width: 75%;
		height: 2.8rem;
		line-height: 2.8rem;
		border-radius: 0.94rem;
		background-color: rgba(239, 239, 239, 1);
		color: rgba(16, 16, 16, 1);
		font-size: 0.88rem;
		text-align: center;
		border: 1px solid rgba(187, 187, 187, 1);
	}

	.popup-container {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, .5);
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.popup-content {
		width: 10.88rem;
		height: 2.69rem;
		line-height: 2.96rem;
		border-radius: 0.94rem;
		background-color: rgba(16, 16, 16, 1);
		font-size: 0.88rem;
		color: #fff;
	}


	.popup-container1 {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, .5);
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.popup-content1 {
		// width: 70%;
		width: 520rpx;
		background-color: white;
		padding: 20px;
		border-radius: 10px;
		box-sizing: border-box;
	}

	.popup-image1 {
		width: 7.5rem;
		height: 7.5rem;
		border-radius: 50%;
	}

	.tip-style1 {
		// height: 1.25rem;
		word-break: break-all;
		line-height: 1.25rem;
		color: rgba(16, 16, 16, 1);
		font-size: 0.88rem;
		text-align: center;
	}

	.popup-button1 {
		width: 6.13rem;
		height: 2rem;
		line-height: 2rem;
		border-radius: 0.5rem 0.5rem 0.5rem 0.5rem;
		background-color: rgba(222, 134, 143, 1);
		color: rgba(255, 255, 255, 1);
		font-size: 0.88rem;
		text-align: center;
		margin-top: 1.5rem;
		margin-bottom: 0.5rem;
		border: none;
	}
</style>